using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;
using System.Text;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DocumentsController : ControllerBase
    {
        private readonly IDocumentService _documentService;

        public DocumentsController(IDocumentService documentService)
        {
            _documentService = documentService;
        }

        /// <summary>
        /// 获取所有文档
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<object>>> GetAllDocuments()
        {
            var documents = await _documentService.GetAllAsync();
            var result = documents.Select(d => new
            {
                id = d.Id,
                name = d.Name,
                fileName = d.FileName,
                type = d.Type,
                size = d.Size,
                permission = d.Permission,
                createdAt = d.CreatedAt,
                updatedAt = d.UpdatedAt,
                uploaderId = d.UploaderId
            });
            return Ok(result);
        }

        /// <summary>
        /// 根据ID获取文档
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Document>> GetDocument(Guid id)
        {
            var document = await _documentService.GetByIdAsync(id);
            if (document == null)
            {
                return NotFound($"文档 {id} 不存在");
            }
            return Ok(document);
        }

        /// <summary>
        /// 根据上传者ID获取文档列表
        /// </summary>
        [HttpGet("uploader/{uploaderId}")]
        public async Task<ActionResult<IEnumerable<Document>>> GetDocumentsByUploader(Guid uploaderId)
        {
            var documents = await _documentService.GetByUploaderIdAsync(uploaderId);
            return Ok(documents);
        }

        /// <summary>
        /// 根据文档类型获取文档列表
        /// </summary>
        [HttpGet("type/{type}")]
        public async Task<ActionResult<IEnumerable<Document>>> GetDocumentsByType(string type)
        {
            var documents = await _documentService.GetByTypeAsync(type);
            return Ok(documents);
        }

        /// <summary>
        /// 根据状态获取文档列表
        /// </summary>
        [HttpGet("status/{status}")]
        public async Task<ActionResult<IEnumerable<Document>>> GetDocumentsByStatus(string status)
        {
            var documents = await _documentService.GetByStatusAsync(status);
            return Ok(documents);
        }

        /// <summary>
        /// 根据标题搜索文档
        /// </summary>
        [HttpGet("search")]
        public async Task<ActionResult<IEnumerable<Document>>> SearchDocumentsByTitle([FromQuery] string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                return BadRequest("搜索关键词不能为空");
            }

            var documents = await _documentService.SearchByTitleAsync(title);
            return Ok(documents);
        }

        /// <summary>
        /// 获取公开文档列表
        /// </summary>
        [HttpGet("public")]
        public async Task<ActionResult<IEnumerable<Document>>> GetPublicDocuments()
        {
            var documents = await _documentService.GetPublicDocumentsAsync();
            return Ok(documents);
        }

        /// <summary>
        /// 创建新文档
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Document>> CreateDocument([FromBody] CreateDocumentRequest request)
        {
            try
            {
                var document = await _documentService.CreateAsync(
                    request.Name, 
                    request.Type, 
                    request.UploaderId, 
                    request.Status, 
                    request.Permission);
                return CreatedAtAction(nameof(GetDocument), new { id = document.Id }, document);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量创建文档
        /// </summary>
        [HttpPost("batch")]
        public async Task<ActionResult<List<Document>>> BatchCreateDocuments([FromBody] List<CreateDocumentRequest> requests)
        {
            try
            {
                var docData = requests.Select(r => (r.Name, r.Type, r.UploaderId, r.Status, r.Permission)).ToList();
                var documents = await _documentService.BatchCreateAsync(docData);
                return Ok(documents);
            }
            catch (Exception ex)
            {
                return BadRequest($"批量创建文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新文档信息
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateDocument(Guid id, [FromBody] Document document)
        {
            if (id != document.Id)
            {
                return BadRequest("文档ID不匹配");
            }

            try
            {
                await _documentService.UpdateAsync(document);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除文档
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteDocument(Guid id)
        {
            try
            {
                await _documentService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理文档
        /// </summary>
        [HttpPost("{id}/process")]
        public async Task<IActionResult> ProcessDocument(Guid id)
        {
            try
            {
                await _documentService.ProcessDocumentAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"处理文档失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置文档权限
        /// </summary>
        [HttpPut("{id}/permission")]
        public async Task<IActionResult> SetDocumentPermission(Guid id, [FromBody] SetPermissionRequest request)
        {
            try
            {
                await _documentService.SetPermissionAsync(id, request.Permission);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"设置权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置文档状态
        /// </summary>
        [HttpPut("{id}/status")]
        public async Task<IActionResult> SetDocumentStatus(Guid id, [FromBody] SetStatusRequest request)
        {
            try
            {
                await _documentService.SetStatusAsync(id, request.Status);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"设置状态失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 解析文档内容
        /// </summary>
        [HttpPost("parse")]
        public async Task<ActionResult<DocumentParseResponse>> ParseDocument([FromForm] IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "请提供要解析的文件"
                    });
                }

                // 文件大小限制 (100MB)
                const long maxFileSize = 100 * 1024 * 1024;
                if (file.Length > maxFileSize)
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "文件大小不能超过100MB"
                    });
                }

                // 支持的文件类型
                var supportedExtensions = new[] { ".txt", ".md", ".html", ".htm", ".doc", ".docx", ".pdf", ".json", ".xml", ".csv" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                
                if (!supportedExtensions.Contains(fileExtension))
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = $"不支持的文件类型: {fileExtension}。支持的格式: {string.Join(", ", supportedExtensions)}"
                    });
                }

                // 读取文件内容
                byte[] fileContent;
                using (var memoryStream = new MemoryStream())
                {
                    await file.CopyToAsync(memoryStream);
                    fileContent = memoryStream.ToArray();
                }

                // 解析文档内容
                var content = await ParseFileContent(fileContent, file.FileName);

                if (string.IsNullOrWhiteSpace(content))
                {
                    return Ok(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "无法从文件中提取有效内容"
                    });
                }

                return Ok(new DocumentParseResponse
                {
                    Success = true,
                    FileName = file.FileName,
                    FileSize = file.Length,
                    FileType = fileExtension,
                    Content = content,
                    ContentLength = content.Length,
                    ParsedAt = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new DocumentParseResponse
                {
                    Success = false,
                    ErrorMessage = $"解析文档时发生错误: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 通过URL解析在线文档
        /// </summary>
        [HttpPost("parse/url")]
        public async Task<ActionResult<DocumentParseResponse>> ParseDocumentFromUrl([FromBody] ParseUrlRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Url))
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "请提供有效的URL"
                    });
                }

                if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var uri))
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "URL格式无效"
                    });
                }

                using var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(30);

                // 下载文件内容
                var response = await httpClient.GetAsync(uri);
                if (!response.IsSuccessStatusCode)
                {
                    return BadRequest(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = $"无法下载文件: {response.StatusCode}"
                    });
                }

                var fileContent = await response.Content.ReadAsByteArrayAsync();
                var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream";
                
                // 尝试从URL获取文件名
                var fileName = Path.GetFileName(uri.AbsolutePath);
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = "document.txt";
                }

                // 解析内容
                var content = await ParseFileContent(fileContent, fileName);

                if (string.IsNullOrWhiteSpace(content))
                {
                    return Ok(new DocumentParseResponse
                    {
                        Success = false,
                        ErrorMessage = "无法从URL内容中提取有效文本"
                    });
                }

                return Ok(new DocumentParseResponse
                {
                    Success = true,
                    FileName = fileName,
                    FileSize = fileContent.Length,
                    FileType = Path.GetExtension(fileName).ToLowerInvariant(),
                    Content = content,
                    ContentLength = content.Length,
                    ParsedAt = DateTime.UtcNow,
                    SourceUrl = request.Url
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new DocumentParseResponse
                {
                    Success = false,
                    ErrorMessage = $"解析在线文档时发生错误: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 解析文件内容
        /// </summary>
        private async Task<string> ParseFileContent(byte[] fileContent, string fileName)
        {
            await Task.CompletedTask;

            try
            {
                var extension = Path.GetExtension(fileName).ToLowerInvariant();
                
                switch (extension)
                {
                    case ".txt":
                        return Encoding.UTF8.GetString(fileContent);

                    case ".md":
                        var markdownContent = Encoding.UTF8.GetString(fileContent);
                        return ExtractTextFromMarkdown(markdownContent);

                    case ".html":
                    case ".htm":
                        var htmlContent = Encoding.UTF8.GetString(fileContent);
                        return ExtractTextFromHtml(htmlContent);

                    case ".json":
                        var jsonContent = Encoding.UTF8.GetString(fileContent);
                        return ExtractTextFromJson(jsonContent);

                    case ".xml":
                        var xmlContent = Encoding.UTF8.GetString(fileContent);
                        return ExtractTextFromXml(xmlContent);

                    case ".csv":
                        var csvContent = Encoding.UTF8.GetString(fileContent);
                        return ExtractTextFromCsv(csvContent);

                    case ".pdf":
                        return ExtractTextFromPdf(fileContent);

                    case ".doc":
                    case ".docx":
                        return ExtractTextFromWord(fileContent);

                    case ".xls":
                    case ".xlsx":
                        return ExtractTextFromExcel(fileContent);

                    case ".ppt":
                    case ".pptx":
                        return ExtractTextFromPowerPoint(fileContent);

                    case ".rtf":
                        return ExtractTextFromRtf(fileContent);

                    default:
                        // 尝试作为纯文本读取
                        return TryExtractAsPlainText(fileContent, fileName);
                }
            }
            catch (Exception ex)
            {
                var extension = Path.GetExtension(fileName).ToLowerInvariant();
                throw new InvalidOperationException($"解析 {extension} 文件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从Markdown中提取文本
        /// </summary>
        private string ExtractTextFromMarkdown(string markdown)
        {
            if (string.IsNullOrWhiteSpace(markdown))
                return string.Empty;

            // 移除Markdown语法标记
            var lines = markdown.Split('\n');
            var textLines = new List<string>();

            foreach (var line in lines)
            {
                var cleanLine = line.Trim();
                
                // 跳过空行
                if (string.IsNullOrWhiteSpace(cleanLine))
                {
                    textLines.Add("");
                    continue;
                }

                // 移除标题标记
                if (cleanLine.StartsWith("#"))
                {
                    var headerText = cleanLine.TrimStart('#').Trim();
                    textLines.Add(headerText);
                    continue;
                }

                // 移除列表标记
                if (cleanLine.StartsWith("- ") || cleanLine.StartsWith("* ") || cleanLine.StartsWith("+ "))
                {
                    var listText = cleanLine.Substring(2).Trim();
                    textLines.Add(listText);
                    continue;
                }

                // 移除数字列表标记
                if (System.Text.RegularExpressions.Regex.IsMatch(cleanLine, @"^\d+\.\s"))
                {
                    var listText = System.Text.RegularExpressions.Regex.Replace(cleanLine, @"^\d+\.\s", "").Trim();
                    textLines.Add(listText);
                    continue;
                }

                // 移除代码块标记
                if (cleanLine.StartsWith("```") || cleanLine.StartsWith("~~~"))
                {
                    continue;
                }

                // 移除内联代码和链接等格式
                var processedLine = cleanLine;
                processedLine = System.Text.RegularExpressions.Regex.Replace(processedLine, @"`([^`]+)`", "$1");
                processedLine = System.Text.RegularExpressions.Regex.Replace(processedLine, @"\[([^\]]+)\]\([^\)]+\)", "$1");
                processedLine = System.Text.RegularExpressions.Regex.Replace(processedLine, @"\*\*([^\*]+)\*\*", "$1");
                processedLine = System.Text.RegularExpressions.Regex.Replace(processedLine, @"\*([^\*]+)\*", "$1");

                textLines.Add(processedLine);
            }

            return string.Join("\n", textLines);
        }

        /// <summary>
        /// 从HTML中提取文本
        /// </summary>
        private string ExtractTextFromHtml(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
                return string.Empty;

            // 简单的HTML标签移除
            var text = System.Text.RegularExpressions.Regex.Replace(html, @"<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            text = System.Text.RegularExpressions.Regex.Replace(text, @"<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            text = System.Text.RegularExpressions.Regex.Replace(text, @"<[^>]+>", " ");
            text = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ");
            
            return System.Net.WebUtility.HtmlDecode(text).Trim();
        }

        /// <summary>
        /// 从JSON中提取文本
        /// </summary>
        private string ExtractTextFromJson(string json)
        {
            try
            {
                using var document = System.Text.Json.JsonDocument.Parse(json);
                return ExtractTextFromJsonElement(document.RootElement);
            }
            catch
            {
                return json; // 如果解析失败，返回原始内容
            }
        }

        private string ExtractTextFromJsonElement(System.Text.Json.JsonElement element)
        {
            var texts = new List<string>();

            switch (element.ValueKind)
            {
                case System.Text.Json.JsonValueKind.String:
                    texts.Add(element.GetString() ?? "");
                    break;
                case System.Text.Json.JsonValueKind.Object:
                    foreach (var property in element.EnumerateObject())
                    {
                        texts.Add($"{property.Name}: {ExtractTextFromJsonElement(property.Value)}");
                    }
                    break;
                case System.Text.Json.JsonValueKind.Array:
                    foreach (var item in element.EnumerateArray())
                    {
                        texts.Add(ExtractTextFromJsonElement(item));
                    }
                    break;
                default:
                    texts.Add(element.ToString());
                    break;
            }

            return string.Join(" ", texts);
        }

        /// <summary>
        /// 从XML中提取文本
        /// </summary>
        private string ExtractTextFromXml(string xml)
        {
            try
            {
                var doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);
                return doc.InnerText;
            }
            catch
            {
                // 如果XML解析失败，移除标签后返回
                var text = System.Text.RegularExpressions.Regex.Replace(xml, @"<[^>]+>", " ");
                return System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ").Trim();
            }
        }

        /// <summary>
        /// 从CSV中提取文本
        /// </summary>
        private string ExtractTextFromCsv(string csv)
        {
            var lines = csv.Split('\n');
            var textLines = new List<string>();

            foreach (var line in lines)
            {
                if (string.IsNullOrWhiteSpace(line))
                    continue;

                var fields = line.Split(',');
                textLines.Add(string.Join(" | ", fields.Select(f => f.Trim().Trim('"'))));
            }

            return string.Join("\n", textLines);
        }

        /// <summary>
        /// 从PDF中提取文本 (改进版实现)
        /// </summary>
        private string ExtractTextFromPdf(byte[] pdfContent)
        {
            try
            {
                // PDF文档的基础文本提取
                var text = Encoding.UTF8.GetString(pdfContent);
                
                // 查找stream对象和文本内容
                var streamPattern = @"stream\s*\n(.*?)\nendstream";
                var matches = System.Text.RegularExpressions.Regex.Matches(text, streamPattern, 
                    System.Text.RegularExpressions.RegexOptions.Singleline | 
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                
                var extractedTexts = new List<string>();
                
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    if (match.Groups.Count > 1)
                    {
                        var streamContent = match.Groups[1].Value;
                        // 提取可读文本
                        var readableText = ExtractReadableTextFromPdfStream(streamContent);
                        if (!string.IsNullOrWhiteSpace(readableText))
                        {
                            extractedTexts.Add(readableText);
                        }
                    }
                }
                
                var result = string.Join("\n", extractedTexts);
                
                // 如果没有提取到有效内容，尝试简单的文本匹配
                if (string.IsNullOrWhiteSpace(result))
                {
                    var simpleText = System.Text.RegularExpressions.Regex.Replace(text, @"[^\x20-\x7E\u4e00-\u9fff\r\n\t]", " ");
                    var lines = simpleText.Split('\n')
                        .Where(line => !string.IsNullOrWhiteSpace(line) && line.Length > 5)
                        .Select(line => line.Trim())
                        .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith("%"));
                    
                    result = string.Join("\n", lines.Take(50)); // 限制行数避免过长
                }
                
                return string.IsNullOrWhiteSpace(result) 
                    ? "PDF文档解析需要专门的库支持(如iText7)，当前为基础实现，建议上传文本格式文档" 
                    : result;
            }
            catch (Exception ex)
            {
                return $"PDF文档解析失败: {ex.Message}。建议使用专业的PDF解析库或转换为文本格式。";
            }
        }

        /// <summary>
        /// 从PDF流中提取可读文本
        /// </summary>
        private string ExtractReadableTextFromPdfStream(string streamContent)
        {
            try
            {
                // 查找文本操作符(Tj, TJ等)
                var textPattern = @"\(([^)]+)\)\s*T[jJ]";
                var matches = System.Text.RegularExpressions.Regex.Matches(streamContent, textPattern);
                
                var texts = new List<string>();
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    if (match.Groups.Count > 1)
                    {
                        var textContent = match.Groups[1].Value;
                        // 清理文本内容
                        textContent = textContent.Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\t", "\t");
                        if (!string.IsNullOrWhiteSpace(textContent) && textContent.Length > 1)
                        {
                            texts.Add(textContent);
                        }
                    }
                }
                
                return string.Join(" ", texts);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 从Word文档中提取文本 (改进版实现)
        /// </summary>
        private string ExtractTextFromWord(byte[] wordContent)
        {
            try
            {
                // .docx 文件是 ZIP 格式，包含 XML 文件
                using var memoryStream = new MemoryStream(wordContent);
                using var archive = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Read);
                
                // 查找 word/document.xml 文件
                var documentEntry = archive.GetEntry("word/document.xml");
                if (documentEntry == null)
                {
                    return "无法找到Word文档内容";
                }
                
                using var documentStream = documentEntry.Open();
                using var reader = new StreamReader(documentStream);
                var xmlContent = reader.ReadToEnd();
                
                // 解析XML并提取文本
                return ExtractTextFromWordXml(xmlContent);
            }
            catch (Exception ex)
            {
                // 如果是 .doc 格式或解析失败，尝试基础文本提取
                try
                {
                    var text = Encoding.UTF8.GetString(wordContent);
                    // 简单清理二进制内容
                    var cleanText = System.Text.RegularExpressions.Regex.Replace(text, @"[^\x20-\x7E\u4e00-\u9fff\r\n\t]", "");
                    var lines = cleanText.Split('\n')
                        .Where(line => !string.IsNullOrWhiteSpace(line) && line.Length > 3)
                        .Select(line => line.Trim())
                        .Where(line => !string.IsNullOrWhiteSpace(line));
                    
                    var result = string.Join("\n", lines);
                    return string.IsNullOrWhiteSpace(result) 
                        ? $"Word文档解析遇到问题: {ex.Message}。建议使用专业的Word解析库如DocumentFormat.OpenXml" 
                        : result;
                }
                catch
                {
                    return $"Word文档解析失败: {ex.Message}。当前为基础实现，建议使用专业库。";
                }
            }
        }

        /// <summary>
        /// 从Word的XML内容中提取文本
        /// </summary>
        private string ExtractTextFromWordXml(string xmlContent)
        {
            try
            {
                var doc = new System.Xml.XmlDocument();
                doc.LoadXml(xmlContent);
                
                // Word文档的文本主要在 w:t 标签中
                var textNodes = doc.GetElementsByTagName("w:t");
                var textLines = new List<string>();
                
                foreach (System.Xml.XmlNode node in textNodes)
                {
                    if (!string.IsNullOrWhiteSpace(node.InnerText))
                    {
                        textLines.Add(node.InnerText);
                    }
                }
                
                // 获取段落分隔
                var paragraphs = doc.GetElementsByTagName("w:p");
                if (paragraphs.Count > 0)
                {
                    var paragraphTexts = new List<string>();
                    foreach (System.Xml.XmlNode paragraph in paragraphs)
                    {
                        var paragraphText = "";
                        var textNodesInParagraph = paragraph.SelectNodes(".//w:t", GetWordNamespaceManager(doc));
                        if (textNodesInParagraph != null)
                        {
                            foreach (System.Xml.XmlNode textNode in textNodesInParagraph)
                            {
                                paragraphText += textNode.InnerText;
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(paragraphText))
                        {
                            paragraphTexts.Add(paragraphText.Trim());
                        }
                    }
                    return string.Join("\n\n", paragraphTexts);
                }
                
                return string.Join(" ", textLines);
            }
            catch
            {
                // 如果XML解析失败，使用简单的正则表达式提取
                var matches = System.Text.RegularExpressions.Regex.Matches(xmlContent, @"<w:t[^>]*>([^<]+)</w:t>");
                var texts = new List<string>();
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    if (match.Groups.Count > 1 && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
                    {
                        texts.Add(match.Groups[1].Value);
                    }
                }
                return string.Join(" ", texts);
            }
        }

        /// <summary>
        /// 获取Word命名空间管理器
        /// </summary>
        private System.Xml.XmlNamespaceManager GetWordNamespaceManager(System.Xml.XmlDocument doc)
        {
            var nsManager = new System.Xml.XmlNamespaceManager(doc.NameTable);
            nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            return nsManager;
        }

        /// <summary>
        /// 从Excel文档中提取文本
        /// </summary>
        private string ExtractTextFromExcel(byte[] excelContent)
        {
            try
            {
                // .xlsx 文件是 ZIP 格式
                using var memoryStream = new MemoryStream(excelContent);
                using var archive = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Read);
                
                var extractedTexts = new List<string>();
                
                // 查找工作表文件
                var worksheetEntries = archive.Entries.Where(e => e.FullName.StartsWith("xl/worksheets/") && e.FullName.EndsWith(".xml"));
                
                foreach (var entry in worksheetEntries)
                {
                    using var stream = entry.Open();
                    using var reader = new StreamReader(stream);
                    var xmlContent = reader.ReadToEnd();
                    
                    var worksheetText = ExtractTextFromExcelWorksheet(xmlContent);
                    if (!string.IsNullOrWhiteSpace(worksheetText))
                    {
                        extractedTexts.Add($"工作表 {entry.Name}:\n{worksheetText}");
                    }
                }
                
                return extractedTexts.Any() 
                    ? string.Join("\n\n", extractedTexts)
                    : "Excel文档解析需要专门的库支持(如EPPlus)，当前为基础实现";
            }
            catch (Exception ex)
            {
                // 尝试作为旧版Excel格式(.xls)处理
                return TryExtractFromLegacyExcel(excelContent, ex);
            }
        }

        /// <summary>
        /// 从Excel工作表XML中提取文本
        /// </summary>
        private string ExtractTextFromExcelWorksheet(string xmlContent)
        {
            try
            {
                var cells = new List<string>();
                
                // 查找单元格数据
                var cellPattern = @"<c[^>]*><v>([^<]+)</v></c>";
                var matches = System.Text.RegularExpressions.Regex.Matches(xmlContent, cellPattern);
                
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    if (match.Groups.Count > 1)
                    {
                        cells.Add(match.Groups[1].Value);
                    }
                }
                
                // 查找内联字符串
                var inlineStringPattern = @"<is><t>([^<]+)</t></is>";
                var inlineMatches = System.Text.RegularExpressions.Regex.Matches(xmlContent, inlineStringPattern);
                
                foreach (System.Text.RegularExpressions.Match match in inlineMatches)
                {
                    if (match.Groups.Count > 1)
                    {
                        cells.Add(match.Groups[1].Value);
                    }
                }
                
                return string.Join(" | ", cells.Where(c => !string.IsNullOrWhiteSpace(c)));
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 尝试从旧版Excel格式中提取文本
        /// </summary>
        private string TryExtractFromLegacyExcel(byte[] content, Exception originalException)
        {
            try
            {
                var text = Encoding.UTF8.GetString(content);
                var cleanText = System.Text.RegularExpressions.Regex.Replace(text, @"[^\x20-\x7E\u4e00-\u9fff\r\n\t]", " ");
                var lines = cleanText.Split('\n')
                    .Where(line => !string.IsNullOrWhiteSpace(line) && line.Length > 3)
                    .Select(line => line.Trim())
                    .Where(line => !string.IsNullOrWhiteSpace(line));
                
                var result = string.Join("\n", lines.Take(100)); // 限制行数
                return string.IsNullOrWhiteSpace(result) 
                    ? $"Excel文档解析失败: {originalException.Message}。建议使用专业库或转换为CSV格式。"
                    : result;
            }
            catch
            {
                return $"Excel文档解析失败: {originalException.Message}。建议转换为CSV或文本格式。";
            }
        }

        /// <summary>
        /// 从PowerPoint文档中提取文本
        /// </summary>
        private string ExtractTextFromPowerPoint(byte[] pptContent)
        {
            try
            {
                // .pptx 文件是 ZIP 格式
                using var memoryStream = new MemoryStream(pptContent);
                using var archive = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Read);
                
                var extractedTexts = new List<string>();
                
                // 查找幻灯片文件
                var slideEntries = archive.Entries.Where(e => e.FullName.StartsWith("ppt/slides/slide") && e.FullName.EndsWith(".xml"));
                
                foreach (var entry in slideEntries)
                {
                    using var stream = entry.Open();
                    using var reader = new StreamReader(stream);
                    var xmlContent = reader.ReadToEnd();
                    
                    var slideText = ExtractTextFromPowerPointSlide(xmlContent);
                    if (!string.IsNullOrWhiteSpace(slideText))
                    {
                        extractedTexts.Add($"幻灯片 {entry.Name}:\n{slideText}");
                    }
                }
                
                return extractedTexts.Any() 
                    ? string.Join("\n\n", extractedTexts)
                    : "PowerPoint文档解析需要专门的库支持，当前为基础实现";
            }
            catch (Exception ex)
            {
                return TryExtractFromLegacyPowerPoint(pptContent, ex);
            }
        }

        /// <summary>
        /// 从PowerPoint幻灯片XML中提取文本
        /// </summary>
        private string ExtractTextFromPowerPointSlide(string xmlContent)
        {
            try
            {
                var texts = new List<string>();
                
                // 查找文本内容
                var textPattern = @"<a:t>([^<]+)</a:t>";
                var matches = System.Text.RegularExpressions.Regex.Matches(xmlContent, textPattern);
                
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    if (match.Groups.Count > 1 && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
                    {
                        texts.Add(match.Groups[1].Value);
                    }
                }
                
                return string.Join(" ", texts);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 尝试从旧版PowerPoint格式中提取文本
        /// </summary>
        private string TryExtractFromLegacyPowerPoint(byte[] content, Exception originalException)
        {
            try
            {
                var text = Encoding.UTF8.GetString(content);
                var cleanText = System.Text.RegularExpressions.Regex.Replace(text, @"[^\x20-\x7E\u4e00-\u9fff\r\n\t]", " ");
                var lines = cleanText.Split('\n')
                    .Where(line => !string.IsNullOrWhiteSpace(line) && line.Length > 3)
                    .Select(line => line.Trim())
                    .Where(line => !string.IsNullOrWhiteSpace(line));
                
                var result = string.Join("\n", lines.Take(100));
                return string.IsNullOrWhiteSpace(result) 
                    ? $"PowerPoint文档解析失败: {originalException.Message}。建议转换为文本格式。"
                    : result;
            }
            catch
            {
                return $"PowerPoint文档解析失败: {originalException.Message}。建议转换为文本格式。";
            }
        }

        /// <summary>
        /// 从RTF文档中提取文本
        /// </summary>
        private string ExtractTextFromRtf(byte[] rtfContent)
        {
            try
            {
                var rtfText = Encoding.UTF8.GetString(rtfContent);
                
                // RTF格式的基础文本提取
                var text = rtfText;
                
                // 移除RTF控制字符
                text = System.Text.RegularExpressions.Regex.Replace(text, @"\\[a-z]+\d*\s?", " ");
                text = System.Text.RegularExpressions.Regex.Replace(text, @"[{}]", " ");
                text = System.Text.RegularExpressions.Regex.Replace(text, @"\\\*[^;]+;", "");
                text = System.Text.RegularExpressions.Regex.Replace(text, @"\\[^a-z]", "");
                
                // 清理多余空格
                text = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ");
                
                return text.Trim();
            }
            catch (Exception ex)
            {
                return $"RTF文档解析失败: {ex.Message}。建议转换为文本格式。";
            }
        }

        /// <summary>
        /// 尝试将未知格式作为纯文本提取
        /// </summary>
        private string TryExtractAsPlainText(byte[] content, string fileName)
        {
            try
            {
                // 尝试多种编码
                var encodings = new[] { Encoding.UTF8, Encoding.GetEncoding("GB2312"), Encoding.ASCII, Encoding.Unicode };
                
                foreach (var encoding in encodings)
                {
                    try
                    {
                        var text = encoding.GetString(content);
                        
                        // 检查是否包含可读文本
                        var readableChars = text.Count(c => char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsWhiteSpace(c));
                        var totalChars = text.Length;
                        
                        if (totalChars > 0 && (double)readableChars / totalChars > 0.7)
                        {
                            // 清理控制字符
                            var cleanText = System.Text.RegularExpressions.Regex.Replace(text, @"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]", " ");
                            cleanText = System.Text.RegularExpressions.Regex.Replace(cleanText, @"\s+", " ");
                            
                            return cleanText.Trim();
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                
                // 如果所有编码都失败，返回基础信息
                var extension = Path.GetExtension(fileName).ToLowerInvariant();
                return $"无法解析 {extension} 格式的文件。文件大小: {content.Length} 字节。建议使用支持的格式(txt, md, html, json, xml, csv)或转换后再上传。";
            }
            catch (Exception ex)
            {
                return $"文件解析失败: {ex.Message}";
            }
        }
    }

    // 请求模型
    public class CreateDocumentRequest
    {
        public string Name { get; set; } = string.Empty;
        public string Type { get; set; } = string.Empty;
        public Guid UploaderId { get; set; }
        public string Status { get; set; } = "pending";
        public string Permission { get; set; } = "private";
    }

    public class SetPermissionRequest
    {
        public string Permission { get; set; } = string.Empty;
    }

    public class SetStatusRequest
    {
        public string Status { get; set; } = string.Empty;
    }

    /// <summary>
    /// 文档解析响应
    /// </summary>
    public class DocumentParseResponse
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName { get; set; } = string.Empty;

        /// <summary>
        /// 文件大小
        /// </summary>
        public long FileSize { get; set; }

        /// <summary>
        /// 文件类型
        /// </summary>
        public string FileType { get; set; } = string.Empty;

        /// <summary>
        /// 解析后的内容
        /// </summary>
        public string Content { get; set; } = string.Empty;

        /// <summary>
        /// 内容长度
        /// </summary>
        public int ContentLength { get; set; }

        /// <summary>
        /// 解析时间
        /// </summary>
        public DateTime ParsedAt { get; set; }

        /// <summary>
        /// 源URL（如果是从URL解析的）
        /// </summary>
        public string? SourceUrl { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }
    }

    /// <summary>
    /// 从URL解析文档的请求
    /// </summary>
    public class ParseUrlRequest
    {
        /// <summary>
        /// 文档URL
        /// </summary>
        public string Url { get; set; } = string.Empty;
    }
}
